import Qust from "/js/Qust.js";
import { $, $$ } from "/js/JSelect.js";
const qust = Qust.create({
	baseUrl: "http://www.rushmc.top/api/",
});

/* 初始执行 */
if (localStorage.getItem("uid") == undefined) {
	$$.navigateTo("/html/login.html");
}
qust.request({
	url: `album/oneAlbum?userId=${localStorage.getItem("uid")}`,
	method: "GET",
}).then((res) => {
	let albums = res.data.data;
	let albumsTemplate = ``;
	albums.forEach((item, index) => {
		let picsTemplate = ``;
		if (item.pictureList != null) {
			item.pictureList.forEach((pic, key) => {
				picsTemplate += `<div class="container" onclick="window.delImg('${pic.url}',${item.albumId})"><img src="http://www.rushmc.top/${pic.url}" /></div>`;
			});
		}

		albumsTemplate += `<div class="card">
		<h2>${item.title}</h2>
		<div class="pics-area">
			${picsTemplate}
		</div>
		<p style="font-weight: 480; margin-bottom: 5px; color: #575656; box-shadow: 0px -2px 0px #787878">新增图片</p>
		<input type="file" multiple="multiple" accept=".jpg,.gif,.jpeg,.png" onchange="window.uploadImg(event,${item.albumId})" />
	</div>`;
	});

	$("#album-area").setHtml(albumsTemplate);
});

/* 函数定义 */
window.delImg = (filename, albumId) => {
	if (confirm("确定删除该照片吗?")) {
		qust.request({
			url: "deletePic",
			data: {
				filename,
				albumId,
			},
		}).then((res) => {
			$$.showModal({
				title: "删除成功",
				content: `${res.data.msg}`,
			}).then(() => {
				location.reload();
			});
		});
	}
};

window.uploadImg = (e, albumId) => {
	let files = e.target.files;
	if (files.length == 0) return false;

	if (confirm("确定上传吗?")) {
		qust.request({
			url: "upload",
			data: {
				file: files,
				albumId,
			},
		}).then((res) => {
			if (res.data.code === 4000) {
				$$.showModal({
					title: "上传成功",
					content: `${res.data.msg}`,
				}).then(() => {
					location.reload();
				});
			} else {
				$$.showModal({
					title: "上传失败",
					content: `${res.data.msg}`,
				});
			}
		});
	}
};

window.addAlbum = () => {
	let title = prompt("请输入新相册名字");
	qust.request({
		url: "createAlbum",
		data: {
			title,
			userId: localStorage.getItem("uid"),
		},
	}).then(() => {
		$$.showModal({
			title: "删除成功",
			content: `${res.data.msg}`,
		}).then(() => {
			location.reload();
		});
	});
};
